import pika
from config import *
import time,json
from queue import Queue
from threading import Thread
from runserver import StartUp
from random import randint
from helper import Helper
from pprint import pprint

# 实例化

# MQ通道打开 执行任务入口

# 定义队列长度为10
q = Queue(10)

# 线程实例化
def callback(ch, method, properties, body):

    print('Message Queue 通道打开,开始接受新的消息....')

    print( body )

    global task

    task = json.loads( body.decode('ascii'))

    # 执行任务
    if '暂无任务' in json.dumps( task,ensure_ascii=False):

        print('暂无领取任务')

    else:

        # 执行任务
        s = StartUp()

        pprint(
            task
        )

        ch.basic_ack(delivery_tag=method.delivery_tag)  # 告诉生成者，消息处理完成

        s.startRequest( task )


    time.sleep( randint(4,7))


def main( ):

    params = domain_url['mq_config']

    credentials = pika.PlainCredentials(params['login'], params['password'])

    parameters = pika.ConnectionParameters(params['host'],5672,'/',credentials)

    connection = pika.BlockingConnection(parameters)

    channel = connection.channel()


    channel.queue_declare(queue='pdddsr.queue',passive=True,durable=True)
    channel.basic_qos(prefetch_count=1)

    channel.basic_consume(on_message_callback=callback,queue='pdddsr.queue',auto_ack=False)

    try:
        # 通道断开重新调用保证长连接
        channel.start_consuming()

    except Exception as e:
        # 回执任务失败
        # 根据taskid进行任务重置
        data = json.dumps({
            "caijiwancheng": [{
                "pingjiashijian": "",
                "descScore": "",
                "logisticsScore": "",
                "serviceScore": "",
                "dingdanhao": "",
                "task_id": task['id'],
                "state": "3",
                "shop_id": task['shop_id']
            }]
        })

        Helper.returnCommentTask(data)
        print('连接异常情况,回执任务成功:%s'%( task['id'] ))


        print("连接已关闭,进行重新连接",e)

        main()


if __name__ == '__main__':

    # main()
    threads =[]
    # 多线程配置

    num = (extAPP['threadsNum'])

    if not isinstance(num,int) or int(num) >= 10:

        num = 1

    for i in range( num ):

        t = Thread( target=main,args=())

        t.start()
        # print( t )
        threads.append( t )

    for t in threads:

        t.join()


